$(() => {
    const $container = $('body > .container');
    // 书写报告
    $container.on('write', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要书写报告的检查', 'error');
            } else {
                const { examGrid, form } = data;
                //调用接口
                ris.ajax(`/api/report/write/${oids[0]}`).then(result => {
                    if (examGrid) {
                        window.open(`/report/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                    }
                    if (form) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 查看
    $container.on('view', (e, data) => {
        getOids(data, (rowsData) => {
            let reportUrls = rowsData.filter(e => e.isArchive).map(e => e.reportUrl);
            if (reportUrls && reportUrls.length === 0) return true;
            if (reportUrls && reportUrls.length >= 0) {
                reportUrls.forEach(e => {
                    ris.viewReport(e);
                })
            }
            if (rowsData.filter(e => !e.isArchive).length > 0) {
                return true;
            }
        }).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要查看报告的检查', 'error');
            } else {
                ris.ajax(`/api/report/get-report-pdf-files`, { type: 'POST', data: { examIds: oids }, errorMessage: '打印服务启动失败' }).then(result => {
                    if (result.success) {
                        if (result.error) {
                            DevExpress.ui.notify(result.error, 'error');
                        }
                        result.data.forEach(e => {
                            ris.viewReport(e);
                        })
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                })
            }
        }).catch(e => { return; });
    });
    // 打开
    $container.on('open', (e, data) => {
        getReportIds(data).then(reportIds => {
            if (reportIds.length === 0) {
                DevExpress.ui.notify('请选择需要打开报告的检查', 'error');
            } else {
                let reportId = reportIds[0];
                if (!reportId) DevExpress.ui.notify('当前检查尚未书写报告', 'error');
                else {
                    window.open(`/report/detail?oid=${encodeURIComponent(reportId)}`, '_blank');
                }
            }
        })
    });
    //查看图像
    $container.on('viewImage', (_, data) => {
        getOids(data, (rowsData) => {
            let reportImagesPaths = rowsData.filter(e => e.isArchive).map(e => e.reportImagesPath);
            if (reportImagesPaths && reportImagesPaths.length === 0) return true;
            if (reportImagesPaths && reportImagesPaths.length >= 0) {
                reportImagesPaths.forEach(e => {
                    ris.viewImage(e);
                })
            }
            if (rowsData.filter(e => !e.isArchive).length > 0) {
                return true;
            }
        }).then(ids => {
            if (ids.length === 0) {
                DevExpress.ui.notify('请选择需要查看图像的检查', 'error');
            } else {
                ris.ajax('/api/exam/get-dicom-client-url').then(result => {
                    if (result.success && result.data) {
                        let url = result.data;
                        if (result.data.includes('?')) {
                            url += `&examIds=${ids.join(',')}`;
                        } else {
                            url += `?examIds=${ids.join(',')}`;
                        }
                        ris.viewImage(url);
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                });
            }
        })
    });
    // 保存
    $container.on('save', (_, data) => {
        save(data).then(_ => {
            DevExpress.ui.notify('保存成功', 'success');
        });
    });
    // 刷新
    $container.on('refresh', (_, data) => {
        refresh(data);
    });
    // 自动刷新
    $container.on('autoRefresh', (_, data) => {
        const { component, key, intervalKey } = data.data;
        component.itemData.text = autoRefresh(key, intervalKey, () => {
            //获取表格
            refresh(data);
        });
        component.component.repaint();
    });
    // 刷新间隔时间
    $container.on('refreshInterval', (_, data) => {
        const { key, intervalKey } = data.data;
        refreshInterval(key, intervalKey, () => {
            //获取表格
            refresh(data);
        });
    });
    // 提交报告
    $container.on('submit', (_, data) => {
        submit(data).then(() => {
            if (data.form && data.form.getData()?.report?.reportStatus === 2 && ris.verify('报告_审核自审')) {
                $container.trigger('audit', data);
            } else {
                //设置只读
                DevExpress.ui.notify('提交成功', 'success');
                refresh(data);
            }
        });
    });
    // 审核报告
    $container.on('audit', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要审核的检查', 'error');
            } else {
                const { examGrid, form } = data;
                //调用接口
                ris.ajax(`/api/report/audit/${oids[0]}`).then(result => {
                    if (examGrid) {
                        window.open(`/report/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                    }
                    if (form) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 打印
    $container.on('print', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要打印报告的检查', 'error');
            } else {
                const printReport = () => {
                    //调用打印接口
                    ris.ajax(`/api/report/get-report-pdf-files`, { type: 'POST', data: { examIds: oids } }).then(result => {
                        if (result.success) {
                            result.data.forEach(e => {
                                ris.printReport(e);
                            })
                        } else {
                            DevExpress.ui.notify(result.error, 'error');
                        }
                    })
                };
                if (data.form && ris.verify('报告_打印并审核')) {
                    const reportStatus = data.form.getData()?.report?.reportStatus;
                    if ((reportStatus === 2 && ris.verify('报告_审核自审')) || reportStatus === 4 || reportStatus === 6) {
                        submit(data, true).then(() => {
                            refresh(data);
                            printReport();
                        });
                    } else {
                        printReport();
                    }
                } else {
                    printReport();
                }
            }
        });
    });
    // 临时打印报告,不验证是否审核
    $container.on('temporarilyPrint', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要打印报告的检查', 'error');
            } else {
                //调用打印接口
                ris.ajax(`/api/report/get-temp-report-pdf-files`, { type: 'POST', data: { examIds: oids }, errorMessage: '打印服务启动失败' }).then(result => {
                    if (result.success) {
                        if (result.error) {
                            DevExpress.ui.notify(result.error, 'error');
                        }
                        result.data.forEach(e => {
                            ris.printReport(e);
                        })
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                })
            }
        });
    });
    // 标记随访
    $container.on('markFollowUp', (e, data) => {
        getReportIds(data).then(reportIds => {
            if (reportIds.length === 0) {
                DevExpress.ui.notify('请选择需要标记随访的检查', 'error');
            } else {
                //工作流
                $.invokeAction('标记随访', `/api/report/mark-follow-up/${reportIds[0]}`, null, { type: 'GET', actionUrl: '/api/workflow/invoke' }).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('标记随访成功', 'success');
                        refresh(data);
                    }
                });
            }
        });
    });
    // 随访记录
    $container.on('followUpRecord', (e, data) => {
        getReportIds(data).then(reportIds => {
            if (reportIds.length === 0) {
                DevExpress.ui.notify('请选择需要随访的检查', 'error');
            } else {
                //工作流
                $.invokeAction('随访记录', `/api/report/get-follow-up-record`, { reportId: reportIds[0] }, { actionUrl: '/api/workflow/invoke' }).then(result => {
                    if (result.success) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 回访
    $container.on('revisit', (e, data) => {
        getReportIds(data).then(reportIds => {
            if (reportIds.length === 0) {
                DevExpress.ui.notify('请选择需要回访的检查', 'error');
            } else {
                //工作流
                $.invokeAction('回访', `/api/report/revisit`, { reportId: reportIds[0] }, { actionUrl: '/api/workflow/invoke' }).then(result => {
                    if (result.success) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 电子申请单
    $container.on('eApply', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择要操作的数据', 'error');
            } else {
                //工作流
                $.invokeAction('电子申请单', `/api/report/get-e-apply/${oids[0]}`, null, { type: 'GET', actionUrl: '/api/workflow/invoke' }).then(result => {
                    if (result.success) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 电子病历
    $container.on('eMedical', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要查看电子病历的检查', 'error');
            } else {
                //工作流
                $.invokeAction('电子病历', `/api/report/get-e-medical/${oids[0]}`, null, { type: 'GET', actionUrl: '/api/workflow/invoke' }).then(result => {
                    if (result.success) {
                        refresh(data);
                    }
                });
            }
        });
    });
    // 危急值
    $container.on('criticalValue', (e, data) => {
        const { form } = data;
        if (form) {
            const formData = getFormData(form);
            if (!formData) return false;
            let reportId = formData.report.oid;
            //工作流
            $.invokeAction('危急值', `/api/report/get-critical-value/${reportId}`, null, { type: 'POST', actionUrl: '/api/workflow/invoke' }).then(result => {
                if (result.success) {
                    refresh(data);
                }
            });
        }
    });
    // 收藏到
    $container.on('collectTo', (e, data) => {
        //教学
        //特殊病例
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('未选择需要收藏的检查', 'error');
            } else {
                openCollectionMenuPopup(oids, true).then(result => {
                    ris.ajax(`/api/report/collect`, { type: 'POST', data: { menuIds: result, examIds: oids } }).then(res => {
                        DevExpress.ui.notify('收藏成功', 'success');
                    })
                });
            }
        });
    });
    // 取消收藏
    $container.on('cancelCollect', (e, data) => {
        //教学
        //特殊病例
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('未选择取消收藏的检查', 'error');
            } else {
                openCollectionMenuPopup(oids, false).then(result => {
                    ris.ajax(`/api/report/cancel-collect`, { type: 'POST', data: { menuIds: result, examIds: oids } }).then(res => {
                        DevExpress.ui.notify('取消成功', 'success');
                    })
                });
            }
        });
    });
    // 撤回
    $container.on('revoke', (e, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要撤回的检查', 'error');
            } else {
                openRevokeConfirmPopup('撤回原因', '撤回').then(reason => {
                    ris.ajax(`/api/report/revoke/${oids[0]}`, { type: 'POST', data: reason }).then(result => {
                        if (result.success) {
                            DevExpress.ui.notify('撤回成功', 'success');
                            //刷新
                            refresh(data);
                        }
                    });
                });
            }
        });
    });
    // 呼叫下一位
    $container.on('callNext', (_, data) => {
        ris.ajax(`/api/technician/call-next`).then(result => {
            if (result.info) {
                DevExpress.ui.dialog.alert(result.info, '呼叫患者');
            }
            refresh(data);
        });
    });
    // 呼叫患者（具体患者）
    $container.on('call', (_, data) => {
        const { examGrid } = data;
        if (examGrid) {
            let oids = examGrid.getSelectedRowKeys();
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要呼叫的检查', 'error');
            } else {
                //调用接口
                ris.ajax(`/api/technician/call/${oids[0]}`).then(result => {
                    refresh(data);
                });
            }
        }
    });
    // 挂起
    $container.on('suspend', (_, data) => {
        const { examGrid } = data;
        let oids = examGrid.getSelectedRowKeys();
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要挂起的检查', 'error');
        } else {
            //调用取消接口
            //调用invokeAction
            $.invokeAction(
                '挂起',
                `/api/register/pending`,
                { examIds: oids },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    DevExpress.ui.notify('挂起成功', 'success');
                    refreshDataGrid(data);
                }
            });
        }
    });
    //过号
    $container.on('skip', (_, data) => {
        const { examGrid } = data;
        let oids = examGrid.getSelectedRowKeys();
        if (oids.length === 0) {
            DevExpress.ui.notify('请选择需要过号的检查', 'error');
        } else {
            $.invokeAction(
                '过号',
                `/api/technician/pass`,
                { examId: oids[0] },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    refreshDataGrid(data);
                }
            });
        }
    });
    // 报告快速查询
    $container.on('reportQuickFilter', (_, data) => {
        openQuickFilterPopup(`/api/filter/get-filter-by-type/exam`, data.data.ele).then(result => {
            const { params } = data;
            if (params) {
                const { reloadGrid } = params;
                if (reloadGrid instanceof Function) {
                    const { examGrid } = data;
                    examGrid.reload({ filterId: result });
                    reloadGrid(() => {
                        examGrid.reload({ filterId: result })
                    });
                }
            }
        })
    });
    // 技师快速查询
    $container.on('technicianQuickFilter', (_, data) => {
        openQuickFilterPopup(`/api/filter/get-filter-by-type/queuing`, data.data.ele).then(result => {
            const { params } = data;
            if (params) {
                const { reloadGrid } = params;
                if (reloadGrid instanceof Function) {
                    const { examGrid } = data;
                    examGrid.reload({ filterId: result });
                    reloadGrid(() => {
                        examGrid.reload({ filterId: result })
                    });
                }
            }
        })
    });
    // 修正报告
    $container.on('amend', (e, data) => {
        openRevokeConfirmPopup('修正原因', '修正').then(reason => {
            const { form, updateToolbarItems } = data;
            const formData = getFormData(form);
            if (!formData) return false;
            //调用接口
            ris.ajax(`/api/report/amend/${formData.oid}`, { type: 'POST', data: reason }).then(result => {
                if (result.success) {
                    refreshForm(data);
                }
            });
        });
    });
    // 驳回重写
    $container.on('reject', (e, data) => {
        openRevokeConfirmPopup('驳回原因', '驳回').then(reason => {
            const { form } = data;
            const formData = getFormData(form);
            if (!formData) return false;
            //调用接口
            ris.ajax(`/api/report/reject/${formData.oid}`, { type: 'POST', data: reason }).then(result => {
                if (result.success) {
                    DevExpress.ui.dialog.alert('驳回重写成功，单击【OK】按钮后将关闭此页面', '提示').then(e => {
                        //关闭页面
                        window.close();
                    });
                }
            });
        });
    });
    // 切换报告样式
    $container.on('changeReportStyle', (_, data) => {
        //更新报告样式
        const { form } = data;
        if (form) {
            const formData = getFormData(form);
            if (formData) {
                let extending = formData.report.reportExtending;
                let schema = formData.report.reportExtendingSchema;

                if (extending) {
                    extending = JSON.stringify(extending);
                }

                if (schema) {
                    schema = JSON.stringify(schema);
                }

                const report = {
                    ...formData.report,
                    reportStyle: { id: data.data.id },
                    reportExtending: extending,
                    reportExtendingSchema: schema
                };

                ris.ajax(`/api/report/${formData.report.oid}/update-report-style`, {
                    type: 'PUT',
                    data: { reportDto: report }
                }).then(result => {
                    if (result.success) {
                        //刷新
                        refresh(data);
                    }
                });
            }

        }
    });
    // 显示视频窗口
    $container.on('showVideoWindow', async (e, data) => {
        if (ris.host && data) {
            const { form, params } = data;
            const formData = getFormData(form);
            if (formData) {
                try {
                    const oid = formData.report.oid;
                    const result = await ris.ajax(`/api/report/${oid}/get-study-base-info`);
                    const currentCapturingId = window.localStorage.getItem('current-video-capturing-id');
                    if (oid == currentCapturingId && formData.report.isEditing && result.data.studyUID) {
                        const tempFile = await ris.host.writeFile(JSON.stringify(result.data));
                        await ris.invokePlugin('VideoDevicePlugin', `open "${result.data.deviceTypeCode}" "${tempFile}"`, true, true);
                        if (params.setCapturingStatus) {
                            params.setCapturingStatus(true);
                        }
                        window.chrome.webview.postMessage(JSON.stringify({
                            type: 'current-capturing-study',
                            data: oid
                        }));
                    } else {
                        await ris.invokePlugin('VideoDevicePlugin', `open "${result.data.deviceTypeCode}"`, true, true);
                    }
                } catch (error) {
                    DevExpress.ui.notify(error, 'error');
                }
            }
        }
    });
    // 设为采集状态
    $container.on('setCapturingStatus', async (e, data) => {
        if (ris.host && data) {
            const { form, params } = data;
            const formData = getFormData(form);
            if (formData && formData.report.isEditing) {
                try {
                    const oid = formData.report.oid;
                    const result = await ris.ajax(`/api/report/${oid}/get-study-base-info`);
                    if (result.data.studyUID) {
                        const tempFile = await ris.host.writeFile(JSON.stringify(result.data));
                        await ris.invokePlugin('VideoDevicePlugin', `open "${result.data.deviceTypeCode}" "${tempFile}"`, true, true);
                        if (params.setCapturingStatus) {
                            params.setCapturingStatus(true);
                        }
                        window.chrome.webview.postMessage(JSON.stringify({
                            type: 'current-capturing-study',
                            data: oid
                        }));
                        window.localStorage.setItem('current-video-capturing-id', oid);
                    } else {
                        DevExpress.ui.notify("当前设备不支持自动生成检查UID，无法设为采集状态", 'error');
                    }
                } catch (error) {
                    DevExpress.ui.notify(error, 'error');
                }
            }
        }
    });
    // 添加备注
    $container.on('addRemark', (_, data) => {
        openAddRemarkPopup(data).then(json => {
            const { params } = data;
            if (params) {
                const { examId } = params;
                if (examId) {
                    ris.ajax(`/api/add-exam-remark`, {
                        type: 'POST',
                        data: {
                            ...json,
                            exam: examId
                        }
                    }).then(e => {
                        if (e.success) {
                            refresh(data);
                        }
                    });
                }
            }
        });
    });
    $container.on('deleteRemark', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要删除的备注', 'error');
            } else {
                //调用删除接口
                DevExpress.ui.dialog.confirm('确定要删除所选的备注吗？', '删除').done(result => {
                    if (result) {
                        ris.ajax(`/api/delete-exam-remark`, { data: { oid: oids[0] }, type: 'POST' }).then(result => {
                            refreshDataGrid(data);
                        });
                    }
                });
            }
        });
    });
    $container.on('updateRemark', (_, data) => {
        if (data) {
            const { examGrid } = data;
            if (examGrid) {
                let itemDatas = examGrid.getSelectedRowsData();
                if (itemDatas.length === 0) {
                    DevExpress.ui.notify('请选择要更新的数据', 'error');
                } else {
                    openAddRemarkPopup(data, itemDatas[0]).then(json => {
                        const { params } = data;
                        if (params) {
                            const { examId } = params;
                            if (examId) {
                                ris.ajax(`/api/update-exam-remark`, {
                                    type: 'POST',
                                    data: {
                                        ...json,
                                        exam: examId
                                    }
                                }).then(e => {
                                    if (e.success) {
                                        refresh(data);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
    });
    // 开始检查
    $container.on('start', (_, data) => {
        if (data) {
            const { examGrid } = data;
            if (examGrid) {
                let oids = examGrid.getSelectedRowKeys();
                if (oids.length === 0) {
                    DevExpress.ui.notify('请选择需要开始检查的检查', 'error');
                } else {
                    ris.ajax(`/api/technician/${oids[0]}/start-exam`).then(result => {
                        if (result.success) {
                            // window.localStorage.setItem('current-video-capturing-id', result.data);
                            window.open(`/report/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                        }
                    });
                }
            }
        }
    });
    // 放弃书写
    $container.on('giveUpWrite', (_, data) => {
        const { form } = data;
        const formData = getFormData(form);
        if (formData) {
            //调用接口
            DevExpress.ui.dialog.confirm('当前已书写的内容不会保存，确定放弃书写吗？', '放弃书写').done(result => {
                if (result) {
                    ris.ajax(`/api/report/give-up-write-report`, { type: 'POST', data: { reportId: formData.report.oid } }).then(result => {
                        if (result.success) {
                            DevExpress.ui.dialog.alert('放弃书写成功，单击【OK】按钮后将关闭此页面', '提示').then(e => {
                                //关闭页面
                                window.close();
                            });
                        }
                    });
                }
            });
        }
    })
    // 移交
    $container.on('transfer', (_, data) => {
        getReportIds(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要移交的报告', 'error');
            }
            else {
                if (oids.filter(e => !e).length > 0) {
                    DevExpress.ui.notify('当前检查尚未书写报告，不需要移交', 'error');
                    return;
                }
                else {
                    $.invokeAction(
                        '移交验证视图',
                        `/api/report/transter`,
                        { reportIds: oids },
                        { actionUrl: '/api/workflow/invoke' }
                    ).then(result => {
                        if (result.success) {
                            DevExpress.ui.notify('移交成功', 'success');
                            refreshDataGrid(data);
                        }
                    });
                }
            }
        });
    })
    //删除
    $container.on('delete', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择要删除的检查', 'error');
            } else {
                //调用删除接口
                $.invokeAction(
                    '删除',
                    `/api/register/delete`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('删除成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    $container.on('applyConsultation', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length != 1) {
                DevExpress.ui.notify('请选择需要申请会诊的检查', 'error');
            } else {
                //调用删除接口
                $.invokeAction(
                    '申请会诊',
                    `/api/study/apply-consultation`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('申请成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    $container.on('disassemble', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要拆分报告的检查', 'error');
            } else {
                // 展示检查项目列表  可以不选择任何检查项目，给出确认提示
                openExamItemPopup(oids[0], async (examItemIds) => {
                    let result = await ris.ajax('/api/report/disassemble', { data: { examId: oids[0], examItemIds }, type: 'POST' });
                    result = await ris.ajax(`/api/report/write/${result.data}`);
                    if (!data.form) {
                        refreshDataGrid(data);
                    }
                    window.open(`/report/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                    return true;
                });
            }
        });
    });
    $container.on('searchQueue', (_, data) => {
        const { reloadGrid } = data.params;
        if (reloadGrid instanceof Function) {
            const { examGrid } = data;
            if (examGrid) {
                const { status } = data.data;
                if (status) {
                    examGrid.refresh({ userData: { status } });
                    reloadGrid(() => {
                        examGrid.refresh({ userData: { status } })
                    });
                }
            }
        }
    });
    $container.on('examEvent', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择查看检查事件的检查', 'error');
            } else if (oids.length !== 1) {
                DevExpress.ui.notify('请选择一条查看检查事件数据', 'error');
            } else {
                openExamEventPopup(oids[0])
            }
        });
    });
    // 导出图像
    $container.on('outputImage', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要导出图像的检查', 'error');
            } else {
                const outputImage = (confirm) => {
                    ris.ajax('/api/exam/output-image', { data: { examIds: oids, confirm }, type: 'POST' }).then(result => {
                        if (result.url) {
                            window.open(result.url, '_blank');
                        } else if (result.info) {
                            DevExpress.ui.notify(result.info, 'success');
                        } else if (result.confirm) {
                            DevExpress.ui.dialog.confirm(result.confirm, '导出图像').done(result => {
                                if (result) {
                                    outputImage(true);
                                }
                            });
                        }
                    });
                };
                outputImage();
            }
        });
    });
    $container.on('export', (_, data) => {
        const { params } = data;
        if (params) {
            const { exportData } = params;
            if (exportData instanceof Function) {
                exportData((loadOptions) => {
                    const exportList = () => {
                        ris.ajax('/api/report/export', { data: loadOptions, type: 'POST', contentType: 'application/json;charset=UTF-8', dataType: 'json' }).then(result => {
                            if (result.data) {
                                window.open(`/api/export-list/${result.data}?fileName=检查表`, '_blank');
                            }
                        });
                    };
                    if (data.examGrid.totalCount() > 1000) {
                        DevExpress.ui.dialog.confirm("导出数据过多，是否继续导出？", "导出列表").done(result => {
                            if (result) {
                                exportList();
                            }
                        })
                    } else {
                        exportList();
                    }
                })
            }
        }
    });
    // 转发图像
    $container.on('relayImage', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length != 1) {
                DevExpress.ui.notify('请选择需要转发图像的检查', 'error');
            } else {
                $.invokeAction(
                    '转发图像',
                    `/api/exam/relay-image`,
                    { examIds: oids },
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('转发图像成功', 'success');
                    }
                });
            }
        });
    });
    // 重新生成报告
    $container.on('remake', (_, data) => {
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要重制报告的检查', 'error');
            } else {
                ris.ajax(`/api/report/remake-report-pdf-files`, { type: 'POST', data: { examIds: oids } }).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('报告已重制', 'success');
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                })
            }
        })
    });
    // 函数
    const verifyArchive = (data) => {
        return new Promise((resolve, reject) => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            if (rowsData && rowsData.length > 0) {
                var isArchive = rowsData.filter(e => e.isArchive);
                if (isArchive.length > 0) {
                    DevExpress.ui.notify('存在已归档的数据', 'error');
                    reject();
                }
            }
            resolve();
        })
    }
    // 获取Oids
    const getOids = (data,func) => {
        return new Promise((resolve,reject) => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            if (func && func instanceof Function && rowsData) {
                let reuslt = func(rowsData);
                if (!reuslt) {
                    reject();
                }
            }
            let oids = rowsData? rowsData.filter(e => !e.isArchive).map(e => e.oid):[];
            if ((!oids) || oids.length === 0) {
                // 获取行数据||form
                getOid(data).then(result => {
                    resolve(result ? [result] : []);
                })
            } else {
                resolve(oids ? oids : []);
            }
        })
    }
    // 获取Oid
    const getOid = (data) => {
        return new Promise((resolve, reject) => {
            let oid = undefined;
            //key
            if (data.data) {
                oid = data.data.oid;
            }
            if (!oid) {
                //获取表格||form中的Oid
                const { form } = data;
                let formData = getFormData(form);
                if (formData) {
                    oid = formData.oid;
                }
            }
            resolve(oid);
        });
    };
    // 获取form数据
    const getFormData = (form) => {
        return !form ? console.error('未获取到form对象') : $.isEmptyObject(form.getData()) ? console.error('form对象为空对象') : form.getData();
    };
    //打开收藏列表
    const openCollectionMenuPopup = (examIds, collect) => {
        return new Promise((resolve, reject) => {
            let collectionMenu = undefined;
            const popup = $('<div>').appendTo('body')
                .dxPopup({
                    width: '45%',
                    height: '65%',
                    container: 'body',
                    showTitle: true,
                    title: collect ? '收藏检查' : '取消收藏',
                    visible: true,
                    dragEnabled: false,
                    toolbarItems: [
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '确定',
                                onClick: () => {
                                    if (collectionMenu) {
                                        const menus = collectionMenu.getSelectedNodes();
                                        let selectedMenuIds = menus.filter(e => e.children.length === 0).map(e => e.key);
                                        //确定匹配
                                        resolve(selectedMenuIds);
                                        popup.hide();
                                    }
                                },
                            },
                        },
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '取消',
                                onClick: () => {
                                    popup.hide();
                                },
                            },
                        },
                    ],
                    position: {
                        //at: 'left bottom',
                        //my: 'left top',
                        at: 'center',
                        my: 'center',
                        collision: 'fit',
                        //of: ele
                    },
                    contentTemplate: container => {
                        ris.ajax(`/api/report/get-collection-menu`, { type: 'POST', data: { examIds, collect } }).then(result => {
                            collectionMenu = $('<div />').appendTo(container).dxTreeView({
                                items: result.data,
                                keyExpr: 'id',
                                displayExpr: 'text',
                                selectedExpr: 'collected',
                                parentIdExpr: 'parentId',
                                dataStructure: 'plain',
                                animationEnabled: false,
                                focusStateEnabled: false,
                                showCheckBoxesMode: 'normal'
                            }).dxTreeView('instance');
                        })
                    },
                    onHidden(e) {
                        //关闭时销毁
                        e.component.dispose();
                        $(e.element).remove();
                    },
                }).dxPopup('instance');
        })
    };

    const refreshForm = (data) => {
        const { form } = data;
        let formData = getFormData(form);
        if (formData) {
            let oid = formData.report.oid;
            ris.ajax(`/api/report/get-exam/${oid}`).then(result => {
                const { form } = data;
                if (result.data.report.permissions.length === 0) {
                    result.data.report.isEditing = false;
                }
                let schema = result.data.report.reportExtendingSchema;
                if (schema) {
                    result.data.report.reportExtendingSchema = JSON.parse(schema);
                }
                let extending = result.data.report.reportExtending;
                if (extending) {
                    result.data.report.reportExtending = JSON.parse(extending);
                }
                let reportId = result.data.report.oid;
                $.get(`/api/report/image-quality-options?reportId=${reportId}`).then((res) => {
                    result.data.report.imageQulitayOptions = res;
                    form.setData(result.data);
                    const { updateToolbarItems } = data;
                    if (updateToolbarItems && updateToolbarItems instanceof Function) {
                        updateToolbarItems(result.data.report);
                    }

                    $container.data('reportOid', oid);
                    $container.data('reportEditing', result.data.report.isEditing);
                    $container.trigger('onReportChanged', result.data.report);

                    if (result.data.report.reportStatus === 8) {
                        $('.main').addClass('audited');
                    } else {
                        $('.main').removeClass('audited');
                    }

                    if (result.data.isShared && result.data.sharedSign) {
                        $('.main').addClass('shared');
                        $('.report-shared').text(result.data.sharedSign);
                    } else {
                        $('.main').removeClass('shared');
                    }
                });
            })
        }
    }

    const openQuickFilterPopup = (url, ele) => {
        return new Promise((resolve, reject) => {
            let selectFilterId = undefined;
            const popup = $('<div>').appendTo('body')
                .dxPopup({
                    width: '45%',
                    height: '80%',
                    container: 'body',
                    showTitle: true,
                    title: '快速查询',
                    visible: true,
                    dragEnabled: false,
                    toolbarItems: [
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '确定',
                                onClick: () => {
                                    if (selectFilterId) {
                                        resolve(selectFilterId);
                                        popup.hide();
                                    } else {
                                        DevExpress.ui.notify('选择需要过滤的条件', 'error');
                                    }
                                },
                            },
                        },
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '取消',
                                onClick: () => {
                                    popup.hide();
                                },
                            },
                        },
                    ],
                    position: {
                        //at: 'left bottom',
                        //my: 'left top',
                        at: 'center',
                        my: 'center',
                        collision: 'fit',
                        //of: ele
                    },
                    contentTemplate: container => {
                        $(container).quickFilter(
                            url,
                            filterId => {
                                selectFilterId = filterId;
                            },
                            {
                                type: 'GET',
                            }
                        )
                    },
                    onHidden(e) {
                        //关闭时销毁
                        e.component.dispose();
                        $(e.element).remove();
                    },
                }).dxPopup('instance');
        })
    };
    const refreshDataGrid = (data) => {
        //获取表格
        const { params } = data;
        if (params) {
            const { reloadGrid } = params;
            if (reloadGrid instanceof Function) {
                reloadGrid();
            }
        } else {
            const { examGrid } = data;
            if (examGrid) {
                examGrid.refresh();
            }
        }
    }
    const openRevokeConfirmPopup = (label, title) => {
        const $form = $('<div />');
        return $form.dxForm({
            labelLocation: 'left',
            // labelMode: "static",
            items: [{
                dataField: 'reviseType',
                editorType: 'dxSelectBox',
                label: { text: '类型' },
                editorOptions: {
                    dataSource: {
                        load() { return $.get(`/api/get-data-dict-by-name/报告修订类型`) }
                    },
                    displayExpr: 'label',
                    valueExpr: 'value',
                    showClearButton: true,
                },
                validationRules: [{
                    type: 'required',
                    message: '类型必选',
                }]
            }, {
                dataField: 'reason',
                editorType: 'dxTextArea',
                label: { text: label },
                editorOptions: {
                    height: 90,
                    maxLength: 200,
                }
            }],
        }).formPopup({
            title: title,
            maxWidth: 600,
            maxHeight: 350,
        })
    }

    const getReportIds = (data) => {
        return new Promise(resolve => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            let reportIds = rowsData?.map(e => e.reportId);
            console.log(reportIds);
            if ((!reportIds) || reportIds.length === 0) {
                //获取form中的reportId
                let reportId = $container.data('reportOid')
                resolve(reportId ? [reportId] : []);
            } else {
                resolve(reportIds ? reportIds : []);
            }
        })
    }

    const openAddRemarkPopup = (data, formData) => {
        const $form = $('<div />');
        return $form.dxForm({
            formData: formData || {},
            labelLocation: 'left',
            // labelMode: "static",
            items: [{
                dataField: 'level',
                editorType: 'dxSelectBox',
                label: { text: '等级' },
                editorOptions: {
                    dataSource: {
                        load() { return $.get(`/api/get-exam-remark-options`) },
                        byKey(key) { return $.get(`/api/get-exam-remark-${key}`) }
                    },
                    displayExpr: 'label',
                    valueExpr: 'value',
                    showClearButton: true,
                },
                validationRules: [{
                    type: 'required',
                    message: '等级必选',
                }]
            }, {
                dataField: 'content',
                editorType: 'dxTextArea',
                label: { text: '内容' },
                editorOptions: {
                    height: 90,
                    maxLength: 200,
                },
                validationRules: [{
                    type: 'required',
                    message: '内容不能为空',
                }]
            }],
        }).formPopup({
            title: '添加备注',
            maxWidth: 600,
            maxHeight: 350,
        })
    }

    const refresh = (data) => {
        const { form } = data;
        if (form) {
            refreshForm(data);
        } else {
            refreshDataGrid(data);
        }
    }

    const save = (data) => {
        return new Promise((resolve, reject) => {
            const { form } = data;
            if (form) {
                const formData = getFormData(form);
                if (!formData) {
                    reject();
                }
                let extending = formData.report.reportExtending;
                let schema = formData.report.reportExtendingSchema;

                if (extending) {
                    extending = JSON.stringify(extending);
                }

                if (schema) {
                    schema = JSON.stringify(schema);
                }

                const report = {
                    ...formData.report,
                    phoneNumber: formData.patient.phoneNumber,
                    reportExtending: extending,
                    reportExtendingSchema: schema
                };

                //调用接口
                ris.ajax('/api/report/save', { type: 'POST', data: { reportDto: report } }).then(result => {
                    document.title = `${formData.patient?.name ?? formData.accessionNumber} | 报告`;
                    resolve({
                        examId: formData.oid,
                        reportId: result.data
                    });
                }).catch(reject);
            }
        })
    }

    const submit = (data, isPrint) => {
        return new Promise((resolve, reject) => {
            save(data).then(result => {
                //验证
                ris.validateExam(result.examId, 'Report').then(() => {
                    const reportId = result.reportId;
                    const reportStatus = data.form?.getData()?.report?.reportStatus;
                    if (ris.verify('报告_审核自审') && ris.verify('报告_验密审核') && ((reportStatus === 2 && isPrint) || reportStatus === 4)) {
                        const userName = localStorage.getItem('audit-verify-user-name');
                        $.invokeAction(
                            '验密审核',
                            `/api/report/verify-user`,
                            {
                                userName,
                                title: '审核验证',
                                show: true
                            }
                        ).then(result => {
                            if (result.success && result.data?.userId) {
                                localStorage.setItem('audit-verify-user-name', result.data.userName);
                                //调用接口
                                ris.ajax('/api/report/submit', {
                                    type: 'POST', data: {
                                        reportId, auditUserId: result.data.userId, ...data.data
                                    }
                                }).then(result => {
                                    resolve(result);
                                });
                            } else {
                                DevExpress.ui.notify('验证失败，请重试', 'error');
                            }
                        });
                    } else {
                        //调用接口
                        ris.ajax('/api/report/submit', { type: 'POST', data: { reportId, ...data.data } }).then(result => {
                            resolve(result);
                        });
                    }
                }).catch(reject);
            }).catch(reject);
        });
    };

    const openExamItemPopup = (examId, disassemble) => {
        let dataGrid;
        const popup = $(`<div>`)
            .appendTo('body')
            .dxPopup({
                width: '30%',
                height: '40%',
                minWidth: '600px',
                minHeight: '400px',
                container: 'body',
                showTitle: true,
                title: `检查项目`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                toolbarItems: [
                    {
                        location: 'before',
                        toolbar: 'bottom',
                        visible: false,
                        html: `
                            <span style="color:#c0392b;font-size:14px;">
                                <i class="fa fa-info-circle"></i>
                                <span>要有两个及两个以上的项目才可以拆分</span>
                            </span>
                        `,
                    },
                    {
                        location: 'after',
                        toolbar: 'bottom',
                        widget: 'dxButton',
                        options: {
                            text: '确定',
                            onClick: () => {
                                let examItemIds = (dataGrid && dataGrid.getSelectedRowKeys());
                                if (examItemIds.length === 0) {
                                    DevExpress.ui.notify('至少需要选择一个检查项目', 'error');
                                } else if (examItemIds.length === dataGrid.getTotalCount()) {
                                    DevExpress.ui.notify('不能拆分出全部检查项目', 'error');
                                }
                                else {
                                    disassemble(examItemIds).then(() => {
                                        popup.hide();
                                    });
                                }
                            },
                        },
                    },
                    {
                        location: 'after',
                        toolbar: 'bottom',
                        widget: 'dxButton',
                        options: {
                            text: '取消',
                            onClick: () => {
                                popup.hide();
                            },
                        },
                    },
                ],
                contentTemplate: container => {
                    const $contentDiv = $(`<div class='p-c'>`).appendTo(container);
                    //表格
                    dataGrid = $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            remoteOperations: false,
                            selection: {
                                mode: 'multiple'
                            },
                            paging: {
                                enabled: false
                            },
                            pager: {
                                visible: false
                            },
                            onLoad(loadOptions) {
                                //根据data返回的数据查询检查列表
                                return $.get({
                                    url: `/api/examitem/get-exam-items-by-exam/${examId}`
                                }).then(result => {
                                    if (!result.success) {
                                        return Promise.reject(result.error)
                                    }
                                    else {
                                        result.data.columns = [{
                                            dataField: "oid",
                                            visible: false
                                        }, {
                                            dataField: "code",
                                            caption: "编码",
                                            width: 150
                                        }, {
                                            dataField: "name",
                                            caption: "名称",
                                        }, {
                                            dataField: "sharedSign",
                                            caption: "互认",
                                        }];

                                        if (result.data.totalCount <= 1) {
                                            const toolbarItems = popup.option('toolbarItems');
                                            toolbarItems[0].visible = true;
                                            toolbarItems[1].visible = false;
                                            toolbarItems[2].options.text = '关闭';
                                            popup.option('toolbarItems', [...toolbarItems]);
                                            dataGrid.setOption('selection.mode', 'none');
                                        }

                                        return result;
                                    }
                                }).catch(error => Promise.reject(error));
                            },
                        });
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    };
    const openExamEventPopup = (examId) => {
        const popup = $('<div>')
            .appendTo('body')
            .dxPopup({
                width: '40%',
                height: '40%',
                minWidth: '700px',
                minHeight: '500px',
                container: 'body',
                showTitle: true,
                title: `检查事件`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                toolbarItems: [{
                    location: 'after',
                    toolbar: 'bottom',
                    widget: 'dxButton',
                    options: {
                        text: '关闭',
                        onClick: () => {
                            popup.hide();
                        },
                    },
                }],
                contentTemplate: container => {
                    const $contentDiv = $('<div class="p-c"></div>').appendTo(container);
                    //表格
                    $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            paging: { enabled: false },
                            pager: { visible: false },
                            remoteOperations: false,
                            onLoad(loadOptions) {
                                return new Promise((resolve, reject) => {
                                    $.get({
                                        url: `/api/exam-event/get-exam-events?examId=${examId}`,
                                        success: result => {
                                            if (result.success) {
                                                resolve(result)
                                            } else {
                                                reject(result.error);
                                            }
                                        }
                                    });
                                })
                            }
                        });
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    }
});
